jQuery.noConflict();

(function($, PLUGIN_ID) {
    'use strict';

    // create form
    var createFormData = function(data) {
        var array = [];
        for (var key in data) {
            var val = data[key];
            if ($.isArray(val)) {
                for (var i = 0; i < val.length; i++) {
                    array.push(key + '[]=' + encodeURIComponent(val[i]));
                }
            } else {
                array.push(key + '=' + encodeURIComponent(val));
            }
        }
        return array.join('&');
    };
    window.kintonePlugin = {};

    window.kintonePlugin.sendcloud = {
        sendMail: function(to, cc, bcc, mailFrom, subject, plain, html, callback, errback) {
            var data = {};

            var config = kintone.plugin.app.getConfig(PLUGIN_ID);
            if (config && config.apiUser && config.apiKey) {
                data.apiUser = config.apiUser;
                data.apiKey = config.apiKey;
            }

            data.to = to;
            if (cc) {
                data.cc = cc;
            }
            if (bcc) {
                data.bcc = bcc;
            }
            data.from = mailFrom;
            data.subject = subject;
            data.plain = plain;
            if (html) data.html = html;
            var formData = createFormData(data);
            var url = 'http://api.sendcloud.net/apiv2/mail/send';
            kintone.plugin.app.proxy(PLUGIN_ID, url, "POST", {'Content-Type': 'application/x-www-form-urlencoded'}, formData, function(resp, status, header) {
                if (callback) {
                    callback.call(this, resp, status, header);
                }
            }, function(error) {
                if (errback) {
                    errback.call(this, error);
                }
            });
        }
    };

})(jQuery, kintone.$PLUGIN_ID);
